<?php

namespace App\Http\Controllers;

use App\Models\Answer;
use App\Models\Question;
use App\Models\Test;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class GuessController extends Controller
{
    public function index(Request $request)
    {
        /** @var User $user 考生 */
        $user = Auth::user();

        // 进行中的考试
        $test = $user->currentTest();

        if ($test) {
            // 正在进行中的考试未答完，返回答题页
            // if ($test->question_count > $test->answer()->count()) {
            //     return redirect()->route('test');
            // }

            // 交卷
            $test = $test->submit();
        } else {
            // 没有进行中的考试时，获取最后一次考试
            $test = $user->test()->whereNotNull('submit_at')->latest()->first();

            // 一次考试都没有时，返回首页
            if (! $test) {
                return redirect()->route('home');
            }
        }

        // 获取考试错题
        $questions = collect();
        if (! $test->is_all_right) {
            // 用户提交的答案
            $answers = Test::getAnswersFromCache($user->id, $test->id);

            // 错题
            $wrongQuestions = Question::getFromCache(
                array_diff($test->questions, $answers->where('is_right', true)->keys()->toArray())
            );

            // 填充用户答案
            $questions = collect($wrongQuestions)->map(function (Question $question) use ($answers) {
                /** @var Answer|array $answer */
                $answer = $answers->get($question->id);

                $question->setAttribute('user_answer', $answer ? $answer['answer'] : []);

                return $question;
            });
        }

        // 清除当前考试缓存
        Cache::forget('test_for_user_' . $user->id);
        Cache::forget('answer_for_user_' . $user->id . '_test_' . $test->id);

        return view('h5.guess_score', compact('user', 'test', 'questions'));
    }
}
